package com.alibaba.nacos.naming.consistency.ephemeral.distro.v2;

import com.alibaba.nacos.api.remote.RequestCallBack;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.common.remote.client.grpc.GrpcClusterClient;
import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
import com.alibaba.nacos.core.distributed.distro.component.DistroCallback;
import com.alibaba.nacos.core.distributed.distro.component.DistroTransportAgent;
import com.alibaba.nacos.core.distributed.distro.entity.DistroData;
import com.alibaba.nacos.naming.cluster.remote.request.DistroDataRequest;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class DistroClientTransportAgent implements DistroTransportAgent {

    @Autowired
    private GrpcClusterClient grpcClusterClient;

    @Autowired
    private ServerMemberManager serverMemberManager;

    @SneakyThrows
    @Override
    public void syncData(DistroData distroData,
                         String targetServer,
                         DistroCallback callback) {
        Member member = serverMemberManager.find(targetServer);
        if (member == null) {
            callback.onSuccess();
            log.warn("targetServer not found: {}", targetServer);
            return;
        }

        DistroDataRequest distroDataRequest = new DistroDataRequest(distroData, distroData.getType());

        RequestCallBack requestCallBack = new RequestCallBack() {
            @Override
            public void onResponse(Response response) {
                log.info("com.alibaba.nacos.api.remote.RequestCallBack.onResponse {}", response);
            }

            @Override
            public void onException(Throwable e) {
                log.error("com.alibaba.nacos.api.remote.RequestCallBack.onException ", e);
            }
        };


        grpcClusterClient.asyncRequest(distroDataRequest, requestCallBack);
    }
}

